<template>
  <div>
    <el-form :model="user" style="width: 400px;padding-top: 50px;padding-left: 220px" status-icon :rules="rules" ref="ruleForm" label-width="200px" class="demo-ruleForm">
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="user.password" auto-complete="off" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="rePassword">
        <el-input type="password" v-model="user.rePassword" auto-complete="off" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import userApi from '@/api/personal/user'
export default {
  name: 'changePassword',
  data () {
    // 密码验证
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.user.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      isLogin: this.$store.state.isLogin,
      user: {
        accountId: this.$store.state.accountId, // 用户编号
        password: '', // 密码
        rePassword: '' // 所确认的密码
      },
      rules: { // 表单验证规则
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ],
        rePassword: [
          {required: true, message: '请再次输入密码', trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    /**
     * 修改按钮点击事件，将user对象作为参数传给api来实现数据的修改，修改成功后跳转到登录界面
     * @param formName 表单名
     */
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          userApi.changePassword(this.user).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.$refs[formName].resetFields()
            this.isLogin = false
            this.$router.push('/login')
          })
        } else {
          this.$message({
            type: 'error',
            message: '请核对两次输入密码是否正确'
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
